package com.easyexcel.demo.strategy;

import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.easyexcel.demo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import java.util.List;
import java.util.Map;


@Slf4j
public class DynamicFieldHandler implements CellWriteHandler {

    // 线程安全的数据容器（替代构造函数注入）
    private static final ThreadLocal<List<UserVO>> DATA_CONTAINER = new ThreadLocal<>();
    private static final int START_ROW = 3;

    // 通过构造函数注入数据集合
    // 通过静态方法设置线程数据（在导出前调用）
    public static void setData(List<UserVO> data) {
        DATA_CONTAINER.set(data);
    }

    // 清理线程变量（导出完成后必须调用）
    public static void clear() {
        DATA_CONTAINER.remove();
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        if (context.getHead()) return;

        List<UserVO> dataList = DATA_CONTAINER.get();
        if (dataList == null) {
            log.info("动态字段处理器未初始化数据");
            return;
        }

        int rowIndex = context.getRowIndex();

        int dataRowIndex = rowIndex - START_ROW;
        if (dataRowIndex < 0) {
            return;
        }
        //前三行表头
        UserVO user = dataList.get(dataRowIndex);
        processDynamicFields(user, context.getRow());
    }

    private void processDynamicFields(UserVO user, Row row) {
        Map<String, UserVO.DynamicField> fields = user.getDynamicFields();
        if (fields == null || fields.isEmpty()) return;

        fields.forEach((key, field) -> {
            safeCreateCell(row, field.getTeacherIndex(), field.getTeacherValue());
            safeCreateCell(row, field.getPeriodIndex(), field.getPeriodValue());
        });
    }

    private void safeCreateCell(Row row, int columnIndex, Object value) {
        Cell cell = row.getCell(columnIndex);
        if (cell == null) {
            cell = row.createCell(columnIndex);
        }
        cell.setCellValue(String.valueOf(value));
    }
}